import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:seedfour/app/checkupdate/update_service.dart';
import 'package:url_launcher/url_launcher.dart';

import 'download_service.dart';



class UpdateDialog extends StatefulWidget {
  final UpdateInfo updateInfo;

  const UpdateDialog({super.key, required this.updateInfo});

  @override
  State<UpdateDialog> createState() => _UpdateDialogState();
}

class _UpdateDialogState extends State<UpdateDialog> {
  DownloadStatus _downloadStatus = DownloadStatus.notStarted;
  double _downloadProgress = 0.0;

  @override
  void initState() {
    super.initState();
    if (GetPlatform.isAndroid) {
      DownloadService.init();
      DownloadService.progressStream.listen((progress) {
        if (mounted) {
          setState(() {
            _downloadProgress = progress;
            if (progress >= 1.0) {
              _downloadStatus = DownloadStatus.completed;
            }
          });
        }
      });

      DownloadService.statusStream.listen((status) {
        if (mounted) {
          setState(() {
            _downloadStatus = status;
          });
        }
      });
    }
  }

  void _startDownload() async {
    if (!mounted) return;

    setState(() {
      _downloadStatus = DownloadStatus.downloading;
    });

    try {
      // EasyLoading.show(status: '准备下载...');
      await DownloadService.downloadApk(
        url: widget.updateInfo.apkUrl,
        fileName: 'app-update-${widget.updateInfo.version}.apk',
      );
      // EasyLoading.dismiss();
    } catch (e) {
      EasyLoading.dismiss();
      if (mounted) {
        setState(() {
          _downloadStatus = DownloadStatus.failed;
        });
        EasyLoading.showError('下载失败: $e');
      }
    }
  }

  String _getFileSize() {
    if (widget.updateInfo.fileSize < 1024) {
      return '${widget.updateInfo.fileSize} B';
    } else if (widget.updateInfo.fileSize < 1048576) {
      return '${(widget.updateInfo.fileSize / 1024).toStringAsFixed(1)} KB';
    } else {
      return '${(widget.updateInfo.fileSize / 1048576).toStringAsFixed(1)} MB';
    }
  }

  Future<void> _openAppStore() async {
    final url = widget.updateInfo.iosAppStoreUrl;
    if (await canLaunchUrl(Uri.parse(url))) {
      await launchUrl(Uri.parse(url));
    } else {
      throw '无法打开App Store: $url';
    }
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Row(
        children: [
          const Icon(Icons.update, color: Colors.blue),
          const SizedBox(width: 10),
          Text('发现新版本 v${widget.updateInfo.version}'),
        ],
      ),
      content: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text('更新内容:', style: TextStyle(fontWeight: FontWeight.bold)),
            const SizedBox(height: 8),
            Text(widget.updateInfo.description),
            const SizedBox(height: 16),
            if (GetPlatform.isAndroid)Text('文件大小: ${_getFileSize()}',style: const TextStyle(color: Colors.grey)),
            if (_downloadStatus != DownloadStatus.notStarted) ...[
              const SizedBox(height: 24),
              _buildDownloadProgress(),
            ],
          ],
        ),
      ),
      actions: _buildActions(),
    );
  }

  Widget _buildDownloadProgress() {
    return Column(
      children: [
        LinearProgressIndicator(
          value: _downloadProgress,
          backgroundColor: Colors.grey[300],
          color: _downloadStatus == DownloadStatus.failed
              ? Colors.red
              : Colors.blue,
          minHeight: 10,
        ),
        const SizedBox(height: 10),
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 8.0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                _downloadStatus == DownloadStatus.downloading
                    ? '正在下载...'
                    : _downloadStatus == DownloadStatus.completed
                    ? '下载完成!'
                    : '下载失败',
                style: TextStyle(
                  color: _downloadStatus == DownloadStatus.failed
                      ? Colors.red
                      : Colors.grey[700],
                ),
              ),
              Text(
                '${(_downloadProgress * 100).toStringAsFixed(1)}%',
                style: const TextStyle(fontSize: 12),
              ),
            ],
          ),
        ),
      ],
    );
  }

  List<Widget> _buildActions() {
    // iOS平台直接跳转App Store
    if (GetPlatform.isIOS) {
      return [
        if (!widget.updateInfo.isForceUpdate) ...[
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('稍后更新'),
          ),
        ],
        ElevatedButton(
          onPressed: _openAppStore,
          child: const Text('前往更新'),
        ),
      ];
    }

    // Android平台处理
    if (_downloadStatus == DownloadStatus.completed) {
      return [
        TextButton(
          onPressed: () => Get.back(),
          child: const Text('稍后安装'),
        ),
        ElevatedButton(
          onPressed: () async {
            try {
              EasyLoading.show(status: '准备安装...');
              await DownloadService.installApk();
              EasyLoading.dismiss();
              Get.back();
            } catch (e) {
              EasyLoading.showError('安装失败: $e');
            }
          },
          child: const Text('立即安装'),
        ),
      ];
    }

    if (_downloadStatus == DownloadStatus.failed) {
      return [
        TextButton(
          onPressed: () => Get.back(),
          child: const Text('取消'),
        ),
        ElevatedButton(
          onPressed: _startDownload,
          child: const Text('重试下载'),
        ),
      ];
    }

    if (_downloadStatus == DownloadStatus.downloading) {
      return [
        TextButton(
          onPressed: () {
            DownloadService.cancelDownload();
            Get.back();
          },
          child: const Text('取消'),
        ),
      ];
    }

    return [
      if (!widget.updateInfo.isForceUpdate) ...[
        TextButton(
          onPressed: () => Get.back(),
          child: const Text('稍后更新'),
        ),
      ],
      ElevatedButton(
        onPressed: _startDownload,
        child: Text(widget.updateInfo.isForceUpdate ? '立即更新' : '下载更新'),
      ),
    ];
  }
}